package flc.ast.fragment;

import android.Manifest;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.StatFs;
import android.text.Html;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import flc.ast.R;
import flc.ast.activity.ApkManagerActivity;
import flc.ast.activity.AudioManageActivity;
import flc.ast.activity.DocManagerActivity;
import flc.ast.activity.FileScanQrActivity;
import flc.ast.activity.ImgDetailActivity;
import flc.ast.activity.PicManageActivity;
import flc.ast.activity.TransferFileActivity;
import flc.ast.activity.VideoDetailActivity;
import flc.ast.activity.VideoManageActivity;
import flc.ast.adapter.RecordKindAdapter;
import flc.ast.adapter.TransferRecordAdapter;
import flc.ast.bean.DrawRecordBean;
import flc.ast.bean.SelectFileBean;
import flc.ast.bean.TransferRecordBean;
import flc.ast.databinding.FragmentFileBinding;
import flc.ast.utils.AppSpUtils;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.device.StorageUtil;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.StatusBarUtils;
import stark.common.basic.utils.StkPermissionHelper;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link FileFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FileFragment extends BaseNoModelFragment<FragmentFileBinding> {

    private List<TransferRecordBean> listShow = new ArrayList<>();
    private TransferRecordAdapter recordAdapter;
    private boolean isEdit = false;
    private int type;
    private Dialog myDeleteDialog;


    @Override
    protected int onCreate() {
        return R.layout.fragment_file;
    }

    @Override
    protected void initView() {
        StatusBarUtils.setSystemStatusTextColor(true, getActivity());
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);


        mDataBinding.ivTransfer.setOnClickListener(this);
        mDataBinding.ivReceive.setOnClickListener(this);
        mDataBinding.tvPicture.setOnClickListener(this);
        mDataBinding.tvVideo.setOnClickListener(this);
        mDataBinding.tvAudio.setOnClickListener(this);
        mDataBinding.tvDocument.setOnClickListener(this);
        mDataBinding.tvApplication.setOnClickListener(this);
        mDataBinding.ivRecordEdit.setOnClickListener(this);
        mDataBinding.ivEditCancel.setOnClickListener(this);
        mDataBinding.ivEditDelete.setOnClickListener(this);
        mDataBinding.tvTransferRecord.setOnClickListener(this);
        mDataBinding.tvReceiveRecord.setOnClickListener(this);

        mDataBinding.rvRecordList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        recordAdapter = new TransferRecordAdapter();
        mDataBinding.rvRecordList.setAdapter(recordAdapter);
        recordAdapter.setOnItemClickListener(this);
        //删除弹框
        deleteDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivTransfer://文件传送
                getTransferPermission();
                break;
            case R.id.ivReceive://文件接收
                getReceivePermission();
                break;
            case R.id.tvPicture://图片管理
                getPicManagePermission();
                break;
            case R.id.tvVideo://视频管理
                getVideoManagePermission();
                break;
            case R.id.tvDocument://文档管理
                startActivity(DocManagerActivity.class);
                break;
            case R.id.tvAudio://音频管理
                startActivity(AudioManageActivity.class);
                break;
            case R.id.tvApplication://应用管路
                startActivity(ApkManagerActivity.class);
                break;
            case R.id.tvTransferRecord://传送记录
                clearSelection();
                type = 1;
                mDataBinding.tvTransferRecord.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.tvTransferRecord.setBackgroundColor(Color.parseColor("#34E0A1"));
                getTransferData();
                break;
            case R.id.tvReceiveRecord://接收记录
                clearSelection();
                type = 2;
                mDataBinding.tvReceiveRecord.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.tvReceiveRecord.setBackgroundColor(Color.parseColor("#34E0A1"));
                getReceiveData();
                break;
            case R.id.ivRecordEdit://编辑
                isEdit = true;
                recordAdapter.setEdit(isEdit);
                recordAdapter.notifyDataSetChanged();
                mDataBinding.ivRecordEdit.setVisibility(View.GONE);
                mDataBinding.llRecordEdit.setVisibility(View.VISIBLE);
                break;
            case R.id.ivEditCancel://取消
                isEdit = false;
                recordAdapter.setEdit(isEdit);
                if (type == 1) {
                    getTransferData();
                } else {
                    getReceiveData();
                }
                mDataBinding.ivRecordEdit.setVisibility(View.VISIBLE);
                mDataBinding.llRecordEdit.setVisibility(View.INVISIBLE);
                break;
            case R.id.ivEditDelete://删除
                myDeleteDialog.show();
                break;
            //删除
            case R.id.ivDialogDeleteConfirm:
                isEdit = false;
                recordAdapter.setEdit(isEdit);
                List<TransferRecordBean> list = recordAdapter.getValidData();
                for (int i = 0; i < list.size(); i++) {
                    TransferRecordBean transferRecordBean = list.get(i);
                    List<SelectFileBean> listKind = transferRecordBean.getList();
                    Iterator<SelectFileBean> iterator = listKind.iterator();
                    while (iterator.hasNext()) {
                        SelectFileBean bean = iterator.next();
                        if (bean.isSelected()) {
                            iterator.remove();
                        }
                    }
                    if (listKind == null || listKind.size() == 0) {
                        list.remove(i);
                    }
                }
                if (type == 1) {
                    AppSpUtils.saveTransferRecordList(list);
                    getTransferData();
                } else {
                    AppSpUtils.saveReceiveRecordList(list);
                    getReceiveData();
                }
                mDataBinding.ivRecordEdit.setVisibility(View.VISIBLE);
                mDataBinding.llRecordEdit.setVisibility(View.INVISIBLE);
                break;
            case R.id.ivDialogDeleteCancel:
                myDeleteDialog.dismiss();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter instanceof RecordKindAdapter) {
            RecordKindAdapter kindAdapter = (RecordKindAdapter) adapter;
            SelectFileBean item = kindAdapter.getItem(position);
            if (isEdit) {
                if (item.isSelected()) {
                    item.setSelected(false);
                } else {
                    item.setSelected(true);
                }
                kindAdapter.notifyDataSetChanged();
            } else {
                if (item.getType() == 1) {
                    ImgDetailActivity.imgPath = item.getPath();
                    startActivity(ImgDetailActivity.class);
                } else if (item.getType() == 2) {
                    VideoDetailActivity.videoPath = item.getPath();
                    startActivity(ImgDetailActivity.class);
                }
            }
        }
    }

    @Override
    protected void initData() {
        StatFs statFs = StorageUtil.getInternalMemory();//内部存储
        //已使用
        long usedLong = statFs.getTotalBytes() - statFs.getAvailableBytes();
        //总内存
        long allLong = statFs.getTotalBytes();
        //已用百分比
        int progress = Math.round((statFs.getTotalBytes() - statFs.getAvailableBytes()) * 100f / statFs.getTotalBytes());
        mDataBinding.tvMemorise.setText(ConvertUtils.byte2FitMemorySize(usedLong, 0) + "/" + ConvertUtils.byte2FitMemorySize(allLong, 0));
        mDataBinding.sbProgress.setProgress(progress);
        getTransferData();
    }

    private void getTransferPermission() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_ALL_MEDIA, Manifest.permission.READ_CONTACTS)
                .reqPermissionDesc(getString(R.string.get_transfer_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        startActivity(TransferFileActivity.class);
                    }

                    @Override
                    public void onDenied(boolean needGoSettings) {
                        ToastUtils.showShort(getString(R.string.no_permission));
                    }
                }).request();
    }

    private void getReceivePermission() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_ALL_MEDIA, Manifest.permission.CAMERA)
                .reqPermissionDesc(getString(R.string.get_receive_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        startActivity(FileScanQrActivity.class);
                    }

                    @Override
                    public void onDenied(boolean needGoSettings) {
                        ToastUtils.showShort(getString(R.string.no_permission));
                    }
                }).request();
    }

    private void getPicManagePermission() {
        StkPermissionHelper.reqManageExternalStoragePermission()
                .reqPermissionDesc(getString(R.string.get_pic_manage_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        startActivity(PicManageActivity.class);
                    }

                    @Override
                    public void onDenied(boolean needGoSettings) {
                        ToastUtils.showShort(getString(R.string.no_permission));
                    }
                }).request();
    }

    private void getVideoManagePermission() {
        StkPermissionHelper.reqManageExternalStoragePermission()
                .reqPermissionDesc(getString(R.string.get_video_manage_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        startActivity(VideoManageActivity.class);
                    }

                    @Override
                    public void onDenied(boolean needGoSettings) {
                        ToastUtils.showShort(getString(R.string.no_permission));
                    }
                }).request();
    }


    private void getTransferData() {
        listShow.clear();
        List<TransferRecordBean> listSp = AppSpUtils.getTransferRecordList();
        if (listSp != null && listSp.size() > 0) {
            listShow.addAll(listSp);
            recordAdapter.setList(listShow);
            mDataBinding.rvRecordList.setVisibility(View.VISIBLE);
            mDataBinding.ivRecordNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvRecordList.setVisibility(View.GONE);
            mDataBinding.ivRecordNoData.setVisibility(View.VISIBLE);
        }
    }

    private void getReceiveData() {
        listShow.clear();
        List<TransferRecordBean> listSp = AppSpUtils.getReceiveRecordList();
        if (listSp != null && listSp.size() > 0) {
            listShow.addAll(listSp);
            recordAdapter.setList(listShow);
            mDataBinding.rvRecordList.setVisibility(View.VISIBLE);
            mDataBinding.ivRecordNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvRecordList.setVisibility(View.GONE);
            mDataBinding.ivRecordNoData.setVisibility(View.VISIBLE);
        }
    }

    private void clearSelection() {
        mDataBinding.tvTransferRecord.setTextColor(Color.parseColor("#D1D1D1"));
        mDataBinding.tvTransferRecord.setBackgroundColor(Color.parseColor("#FFFFFF"));
        mDataBinding.tvReceiveRecord.setTextColor(Color.parseColor("#D1D1D1"));
        mDataBinding.tvReceiveRecord.setBackgroundColor(Color.parseColor("#FFFFFF"));
    }

    //删除弹框
    private void deleteDialog() {
        myDeleteDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_delete, null);
        myDeleteDialog.setContentView(inflate);
        myDeleteDialog.setCancelable(true);
        Window dialogWindow = myDeleteDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView cancel = inflate.findViewById(R.id.ivDialogDeleteCancel);
        ImageView comp = inflate.findViewById(R.id.ivDialogDeleteConfirm);
        TextView tip = inflate.findViewById(R.id.tvDialogDeleteTip);
        // 设置文本及其颜色
        StringBuffer str = new StringBuffer();
        str.append(getString(R.string.delete_tip1));
        str.append("<font color='#FF3838'>" + getString(R.string.delete_tip2) + "</font>");
        str.append(getString(R.string.delete_tip3));
        // 在文本控件中显示
        tip.setText(Html.fromHtml(str.toString(), getImageGetter(), null));
        cancel.setOnClickListener(this);
        comp.setOnClickListener(this);
    }

    private Html.ImageGetter getImageGetter() {
        return source -> {
            Drawable drawable = getActivity().getDrawable(Integer.parseInt(source));
            drawable.setBounds(0, 0, 60, 60);
            return drawable;
        };
    }

}